const Credentials = require('../credentials');

class Config {
    constructor(endpoint, accessKey, secretKey, protocol = 'HTTPS', method = 'POST') {
        this.endpoint = endpoint;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.protocol = protocol;
        this.method = method;
    }
}

class Client {
    constructor(config) {
        if (!config.endpoint) {
            throw new Error('endpoint is required');
        }
        if (!config.accessKey || !config.secretKey) {
            throw new Error('aksk is required');
        }

        this.endpoint = config.endpoint;
        this.accessKey = config.accessKey;
        this.secretKey = config.secretKey;
        this.protocol = config.protocol || 'HTTPS';
        this.method = config.method || 'POST';
    }

    // 添加必要的错误处理
    async doRequest(requestConfig) {
	try {
        const CTAPIrequest = {
            //GET方法查询函数详情 需要拼接URL
            url: `${this.protocol}://${this.endpoint}${requestConfig.url}`,
            endpoint: this.endpoint,
            method: this.method,
            headers: requestConfig.headers,
            data: requestConfig.data,
            query: requestConfig.params,

        };
        const cre = new Credentials(this.accessKey, this.secretKey);
        const response = await cre.doCTAPIRequest(CTAPIrequest);
        // 响应为JSON对象，返回给上级service
        // const res = JSON.parse(response);
        return response;
	} catch (error) {
		console.log('client doRequest response error.')
        console.log('error message:', error);
		console.log('error status: ', error.response.status, 'reason: ', error.response.statusText); 
		return error;
	}
    }
}

module.exports = {
    Config: Config,
    Client: Client
};
